import React, { useState, useEffect, useCallback } from 'react'
import { connect } from 'react-redux'
import basicStyle from './basic.scss'
import { NotifyType } from '../../common/enums'
import { getActiveConfigTypeSelector } from '../../selectors/baseSelector'
import { getAllConfigs } from '../../source/getData'
import { notify } from '../../source/notify'
import { saveConfig } from '../../source/saveData'
import style from './configEditor.scss'
import { ColHeader } from './colHeader'

const maStateToProps = state => {
    return {
        activeConfigType: getActiveConfigTypeSelector(state),
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onSave: (configType, configValue) => saveConfig(configType, configValue)
    }
}

export const ConfigEditor = connect(maStateToProps, mapDispatchToProps)((props) => {
    const { activeConfigType, onSave } = props
    const [loading, setLoading] = useState(false)
    const [allConfigs, setAllConfigs] = useState({})
    const [value, setValue] = useState('')

    const wrapOnChangeValue = useCallback(ev => setValue(ev.target.value), [])
    const wrapOnSave = useCallback(() => {
        onSave(activeConfigType, value)
            .then(({ message }) => {
                setLoading(false)
                if (message) {
                    notify(NotifyType.error, '保存失败：' + message)
                } else {
                    notify(NotifyType.info, '保存成功')
                }
            })
    }, [activeConfigType, value])

    useEffect(() => {
        setLoading(true)
        getAllConfigs()
            .then(data => {
                setLoading(false)
                setAllConfigs(data)
            }).catch(err => {
                setLoading(false)
                setValue([])
                notify(NotifyType.error, err)
            })
    }, [])

    useEffect(() => {
        setValue(JSON.stringify(allConfigs[activeConfigType] || [], null, 2))
    }, [allConfigs, activeConfigType])

    return loading
        ? <div className={basicStyle.basic_loading} />
        : <div >
            <ColHeader title='修改配置（请非常谨慎）：' />
            <div className={basicStyle.actions}>
                <button onClick={wrapOnSave}>保存</button>
            </div>
            <textarea className={style.editor} onChange={wrapOnChangeValue} value={value}></textarea>
        </div>
})